<?php
/**
 * Created by PhpStorm.
 * User: superxing-cto
 * Date: 17/5/9
 * Time: 11:37
 */

namespace App\Models;

/**
 * Class CouponNumber
 * @package App\Models
 * @property integer coupon_id
 * @property integer user_id
 * @property dateTime start_time 开始时间
 * @property dateTime end_time 结束时间
 * @property boolean status 状态：true：可使用、false不可使用
 * @property string get_method 优惠券获取方式
 * @property Coupon coupon 优惠券
 */
class CouponNumber extends ApplicationModel
{
    protected $fillable = [
        'coupon_id',
        'user_id',
        'start_time',
        'end_time',
        'status',
        'get_method',
        'type',
        'send_type',
    ];

    static function boot()
    {
        parent::boot();
        static::creating(function(CouponNumber $couponNumber){
            $couponNumber->before_create();
        });
    }

    public function before_create()
    {
        $coupon = $this->coupon;
        $this->start_time = date('Y-m-d H:i:s');
        $this->end_time = date('Y-m-d H:i:s',strtotime('+'.$coupon->valid_val.' '.$coupon->valid_type));
        $this->status = true;
    }

    public function coupon()
    {
        return $this->belongsTo(Coupon::class)->withTrashed();
    }


    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function scopeUsable($query){
        return $query->where('status',true);
    }

    public function valid_coupon($product_id, $count = 1,$user_id=0)
    {
        $product = Product::find($product_id);
        if (!$product) {
            return false;
        }
        if(!$this->status){
            return false;
        }
        if (strtotime($this->start_time) <= time() && strtotime($this->end_time) >= time()) {
            $coupon = $this->coupon;
           // $price = $product->price * $count;
             $price = $product->discount_price($user_id) * $count;
           // \Log::info($user_id, ['============coupon=====user_id======================']);
           // \Log::info($price, ['============coupon=====price======================']);
            //$price = $total;
            if ($coupon->order_scope <= $price) {
                return $this->coupon_price($price);
            }
        }
        return false;
    }

    public function coupon_price($price)
    {
        $coupon = $this->coupon;
        return $price - $coupon->price;
    }

    public function coupon_real_price()
    {
        return $this->coupon->price;
    }


}